package com.blog.boot.webapp.utils;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtils {
    //一分钟
    private static final long ONEMINUTE = 60000;
    //一小时
    private static final long ANHOUR = 3600000;
    //24小时
    private static final long TWENTYFOURHOURS = 86400000;
    /**
     * 获取请求ip
     */
    public static String getIp(HttpServletRequest request) {
        //代理进来，则透过防火墙获取真实IP地址
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        //如果没有代理，则获取真实ip
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;

    }

    /**
     * 获取系统时间
     */
    public static String getSystemTime(String format) {
        Date data = new Date();
        return new SimpleDateFormat(format).format(data.getTime());
    }

    /**
     * 根据指定的时间返回时间戳
     */
    public static Long returnCustom(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date data = null;
        try {
            data = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (Objects.isNull(data)) {
            return Long.valueOf(0);
        }
        return data.getTime();
    }

    public static String getDatePoor(Date old) {
        Date nowDate = new Date();
        long l1 = nowDate.getTime() - old.getTime();
        long l = l1 / TWENTYFOURHOURS;
        //大于10天就显示原时间
        if( l >= 10 ){
            return new SimpleDateFormat("yyyy-MM-dd").format(old);
        }
        //小于十天显示几天前
        if( l >0 ){
            return l + "天前";
        }
        //几小时前
        long z = l1 / ANHOUR;
        if( z >0 ){
            return z + "小时前";
        }

        long s = l1 / ONEMINUTE;
        //如果分钟数小于5就是刚刚发布
        if( s <= 5 ){
            return "刚刚";
        }
        //几分钟前
        if( s > 0){
            return s+"分钟前";
        }
        return "null";
    }

    /**
     * 合并两个对象的属性
     */
    @SuppressWarnings("unused")
    public static Object combineSydwCore(Object sourceBean, Object targetBean) {
        Class sourceBeanClass = sourceBean.getClass();
        Class targetBeanClass = targetBean.getClass();

        Field[] sourceFields = sourceBeanClass.getDeclaredFields();
        Field[] targetFields = sourceBeanClass.getDeclaredFields();
        for (int i = 0; i < sourceFields.length; i++) {
            Field sourceField = sourceFields[i];
            Field targetField = targetFields[i];
            sourceField.setAccessible(true);
            targetField.setAccessible(true);
            try {
                if (!(sourceField.get(sourceBean) == null)) {
                    targetField.set(targetBean, sourceField.get(sourceBean));
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return targetBean;
    }

    /**
     * 正则匹配
     *
     * @param regex
     * @param str
     * @return
     */
    public static boolean match(String regex, String str) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }

    /**
     * 执行js代码 正文为js字符串
     * 目前只支持一个value参数
     */
    public static Object execJavaScript(String content, String function, String values) {
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("javascript");
        try {
            engine.eval(content);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
        Invocable inv = (Invocable) engine;
        Object res = null;
        try {
            res = inv.invokeFunction(function, values);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
}
